package 蓝桥杯算法;

public class day01 {
    public static void main(String[] args) {
            int a[]={1,2,4,5,6,7,44,66,77};
           day01 b=new day01();
            int x=b.search(a,2);
            System.out.println(x);
            int y=b.search2(a,44);
            System.out.println(y);
            int h=b.removeElement(a,5);
            System.out.println(h);
            int s=b.removeElement2(a,5);
            System.out.println(s);

    }
    public int search(int[] nums,int target){//左闭右闭
        int left=0;
        int right=nums.length-1;
        if(target<nums[0]||target>nums[nums.length-1]){
            return -1;
        }
        while(left<=right){
            int mid=left+((right-left)>>1);
         if(nums[mid]==target){
             return mid;
         }
         else if(nums[mid]>target){
             right=mid-1;
         }
         else {
             left=mid+1;
         }
        }
        return -1;
    }
    public int search2(int[] nums,int target){//左闭右开
        int left=0;
        int right=nums.length-1;
        if(target<nums[0]||target>nums[nums.length-1]){
            return -1;
        }
        while(left<right) {
            int mid = left + ((right - left) >> 1);
            if(nums[mid]==target){
                return mid;
            }
            else if(nums[mid]>target){
                right=mid;
            }
            else{
                left=mid+1;
            }
        }
        return -1;
    }
    public int removeElement(int[] nums,int val){//暴力法
        int n=nums.length;
        for(int i=0;i<n;i++){
            if(nums[i]==val){
                for(int j=i+1;j<n;j++){
                    nums[j-1]=nums[j];
                }
                i--;//由i-1继续往后循环
                n--;
            }
        }
        return n;
    }
    public  int removeElement2(int[] nums,int val){//双指针法
       int slow=0;
       for(int fast=0;fast<nums.length;fast++){
           if(nums[fast]!=val){
               nums[slow]=nums[fast];
               slow++;
           }
       }
       return slow;
    }
}
